<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/7/8 14:15
 */


namespace App\Logic\Common;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Rbac\RbacRole;
use App\Models\Staffer\Staffer;
use Illuminate\Database\Eloquent\Builder;

class RoleLogic extends CommLogic
{
    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = RbacRole::query()
            ->with('tenant')
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', 'like', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }else{
            $query = $query->orderBy('id', 'desc');
        }
        
        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();
        return $data;
    }

    /**
     * @param $params
     * @return array
     */
    public function lists($params)
    {
        $data = RbacRole::query()
            ->with('tenant')
            ->when(isset($params['status']), function (Builder $query) use ($params) {
                $query->where('status', $params['status']);
            })
            ->when(!empty($params['organic_id']), function (Builder $query) use ($params) {
                $query->where('organic_id', $params['organic_id']);
            })
            ->when(!empty($params['name']), function (Builder $query) use ($params) {
                $query->where('name', 'like', '%' . $params['name'] . '%');
            })->get()->toArray();

        return $data;
    }

    /**
     * @param $params
     * @return Role|Builder|\Illuminate\Database\Eloquent\Model
     */
    public function store($params)
    {
        $lockName = 'role_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        $data = array(
            'name' => $params['name'],
            'status' => $params['status'] ? 1 : 0,
            'menus' => implode(',', $params['menus']),
            'tenant_id' => $params['tenant_id'],
            'remark' => $params['remark'] ?? '',
        );
        return RbacRole::query()->create($data);
    }

    /**
     * @param $params
     * @param $id
     * @return Role|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($params, $id)
    {
        $data = RbacRole::query()->with('tenant')->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '角色不存在！');
        $menus = array();
        foreach(explode(',', $data->menus) as $menu){
            $menus[] = intval($menu);
        }
        $data->menus = $menus;
        $data->status = $data->status ? true : false;
        return $data;
    }

    /**
     * @param $params
     * @param $id
     * @return bool|int
     */
    public function update($params, $id)
    {
        $lockName = 'role_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $role = RbacRole::query()->where('id', $id)->first();
        abort_if(empty($role), HttpCode::FORBIDDEN, '角色不存在！');
        $data = array(
            'name' => $params['name'],
            'status' => $params['status'] ? 1 : 0,
            'menus' => implode(',', $params['menus']),
            'tenant_id' => $params['tenant_id'],
            'remark' => $params['remark'] ?? '',
        );
        return RbacRole::query()->where('id', $id)->update($data);
    }

    /**
     * @param $id
     * @return bool|mixed|null
     */
    public function destroy($id)
    {
        $role = RbacRole::query()->where('id', $id)->first();
        abort_if(empty($role), HttpCode::FORBIDDEN, '角色不存在！');
        // $staffer = Staffer::query()->where('role_ids', $id)->first();
        // abort_if(!empty($staffer), HttpCode::FORBIDDEN, '角色还存在！');
        return RbacRole::query()->where('id', $id)->delete();
    }
}
